<?php
  //Last Update		:	2009-03-30
  //Author			:	lsh
  //Ntalker3.0 For uch1.5	

  define('SUB_DIR','/ntalker/');
  @define('IN_UCHOME', TRUE);
  define('X_VER', '1.5');
  define('D_BUG', '0');
  define('S_ROOT', str_replace(SUB_DIR,'/',str_replace('\\','/',dirname(__FILE__).DIRECTORY_SEPARATOR)));

  @include_once S_ROOT.'./config.php';
  @include_once S_ROOT.'./data/data_config.php';
  include_once S_ROOT.'./uc_client/client.php';
  include_once S_ROOT.'./source/function_common.php';
  require_once './imconfig.inc.php';

  $imversion = "3.1.0";
  $imbuild = "20101213";
  
  //接口文件优化系数 high：性能优先；low：扩展性优先
  $imxmlperf = "low";
  
  $mtime = explode(' ', microtime());
  $_SGLOBAL['timestamp'] = $mtime[1];

    $querytype = isset($_GET['query']) ? $_GET['query'] : null;
    $querysid = isset($_GET['sid']) ? $_GET['sid'] : null; 
    $userkey = isset($_GET['userkey']) ? $_GET['userkey'] : null; 
    $queryuserid = isset($_GET['uid']) ? $_GET['uid'] : null;
    $pagesize = isset($_GET['pagesize']) ? $_GET['pagesize'] : null;
    $pageindex = isset($_GET['pageindex']) ? $_GET['pageindex'] : null;
    $isdetail = isset($_GET['isdetail']) ? $_GET['isdetail'] : null;
    $newbuddyid =  isset($_GET['newbuddyid']) ? $_GET['newbuddyid'] : null;
    $delbuddyid =  isset($_GET['delbuddyid']) ? $_GET['delbuddyid'] : null;
    $confirm =  isset($_GET['confirm']) ? $_GET['confirm'] : null;
    $destid =  isset($_GET['destid']) ? $_GET['destid'] : null;
    $time =  isset($_GET['time']) ? $_GET['time'] : null; 
    $newtime =  isset($_GET['newtime']) ? $_GET['newtime'] : null;
    $hottime =  isset($_GET['hottime']) ? $_GET['hottime'] : null;
    $maxnum =  isset($_GET['maxnum']) ? $_GET['maxnum'] : null;
    $moneyrate  = isset($_GET['moneyrate']) ? $_GET['moneyrate'] : null;
    $actionmoney = isset($_GET['actionmoney']) ? $_GET['actionmoney'] : null;
    $actionid = isset($_GET['actionid']) ? $_GET['actionid'] : null;
    $gid =  isset($_GET['gid']) ? $_GET['gid'] : null;
    $groupkey =  isset($_GET['groupkey']) ? $_GET['groupkey'] : null;
    $isuserprofile = isset($_GET['isuserprofile']) ? $_GET['isuserprofile'] : null;
    $isfuidlist = isset($_GET['isfuidlist']) ? $_GET['isfuidlist'] : null;
    $fuids= isset($_GET['fuids']) ? $_GET['fuids'] : null;

    header( "Content-Type: text/xml; charset=utf-8" );
	  echo( "<?xml version='1.0' encoding='utf-8'?>" );
	  echo( "<imxml  encoding='utf-8'>" );

    if(!$querytype){
        echo( "<error>no valid query param</error>" );
        echo( "</imxml>" );
        exit();
    }
   
    switch($querytype){
		case "imxmlversion":
			getImxmlVersion();
            break;
        case "login":
            getLogin($querysid, $queryuserid, $isuserprofile, $isdetail);
            break;
        case "userprofile":
            getUserProfile($querysid, $queryuserid, $userkey, $destid, $isdetail);
            break;
        case "buddylist":
            getBuddyList($querysid, $queryuserid, $userkey, $pagesize, $pageindex, $isfuidlist, $isdetail, $fuids);
            break;
        case "addbuddy":
            getAddBuddy($querysid, $queryuserid, $userkey, $newbuddyid);
            break;
        case "delbuddy":
            getDelBuddy ($querysid, $queryuserid, $userkey, $delbuddyid);
            break;
        case "confirmbuddy":
            getConfirmBuddy($querysid, $queryuserid, $userkey, $newbuddyid, $confirm);
            break;
        case "useractivity":
            getUserActivity($querysid, $queryuserid, $userkey, $destid, $time, $maxnum);
            break;
        case "buddylistactivity":
            getBuddylistActivity($querysid, $queryuserid, $userkey, $time, $maxnum, $pagesize, $pageindex, $fuids);
            break;
        case "siteactivity":
            getSiteActivity($querysid, $queryuserid, $userkey, $newtime, $hottime, $maxnum);
            break;
        case "visitorlist":
            getVisitorlist($querysid, $queryuserid, $userkey, $maxnum);
            break; 
        case "notifyimaction":
            getNotifyImAction($queryuserid, $userkey, $actionid, $moneyrate, $actionmoney);
            break;    
        case "siteprofile":
            getSiteProfile();
            break;
        case "mygroup":
            getMyGroup($querysid, $queryuserid, $userkey, $maxnum);
            break;
        case "groupmemberlist":
            getGroupMemberlist($gid, $groupkey, $pagesize, $pageindex, $queryuserid);
            break;
        case "groupprofile":
            getGroupProfile($gid, $groupkey);
            break;
        case "groupmemberchange":
            getGroupMemberchange($gid, $groupkey);
            break;
        case "groupactivity":
            getGroupActivity($gid, $groupkey, $time, $maxnum);
            break;        
        default:
            echo( "<error>query param is not valid</error>" );
    }
    
    echo( "</imxml>" );
    exit();

    //1-返回IMXML版本号
    function getImxmlVersion(){
         global $imversion,$imbuild;
         echo "<version>".$imversion."</version>";
         echo "<for>UCHhome ".X_VER."</for>";
         echo "<build>".$imbuild."</build>";
         return;
    }
    //2-验证用户是否在论坛网站登录成功
    function  getLogin($querysid, $queryuserid, $isuserprofile=false, $isdetail=false){
         global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $imversion;
         echo '<version>'.$imversion.'</version>';
         if(!$queryuserid || !$querysid){
              echo "<sessionvalide>false</sessionvalide>";
              return false;
         }
         dbconnect();   
         $queryuserid = intval($queryuserid);
         $isdetail = $isdetail ? ($isdetail=="true" ? 1 : 0): 0;
         @list($password, $uid) = explode("\t", im_authcode($querysid, 'DECODE'));
         $_SGLOBAL['supe_uid'] = intval($uid);
         $addtable = $addcoum = '';
         if($isuserprofile){
              $addtable = 'LEFT JOIN '.tname('spacefield').' sf ON sf.uid=s.uid LEFT JOIN '.tname('usergroup').' u ON u.gid=s.groupid';
              if($isdetail){
                   $addcoum = ',s.credit,s.groupid,sf.sex,sf.birthyear,sf.birthmonth,sf.birthday,sf.resideprovince,sf.residecity,sf.email,u.grouptitle';
              }else{
                   $addcoum = ',s.groupid,sf.sex,sf.birthyear,sf.birthmonth,sf.birthday,sf.resideprovince,sf.residecity,u.grouptitle';
              }
         }
         $querysql = "SELECT s.uid,s.username,s.name $addcoum FROM ".tname('space')." s $addtable WHERE s.uid='$queryuserid'";
         $userspace = $_SGLOBAL['db']->fetch_array($_SGLOBAL['db']->query($querysql));
	     if($_SGLOBAL['supe_uid']==$queryuserid && $userspace){
              echo '<sessionvalide>true</sessionvalide>';
              if($isuserprofile){
                   //是否开启实名认证  
                   if($_SCONFIG['realname'] && $userspace['name']){ 
                        $userspace["username"] = im_xmlsafestr(htmlspecialchars($userspace['name']));
                   }else{
                        $userspace["username"] = im_xmlsafestr(htmlspecialchars($userspace['username']));
                   }
                   $usericon = im_avatar($queryuserid,middle);
                   if(empty($_SC['siteurl'])) $_SC['siteurl'] = str_replace(SUB_DIR,'/',getsiteurl());
                   $genders = $userspace['sex']==0 ? -1 : ($userspace['sex']==1 ? "male" : "female");
                   $bday = sprintf('%04d-%02d-%02d', $userspace['birthyear'], $userspace['birthmonth'], $userspace['birthday']);
                   $bday = ($bday=='0000-00-00') ? "" : $bday;
                   echo "<userprofile>";
                       echo "<uid>".$queryuserid."</uid>";
                       echo "<name>".$userspace["username"]."</name>";
                       echo "<icon><![CDATA[".$usericon."]]></icon>";
                       echo "<isdefaulticon>-1</isdefaulticon>";
                       echo "<profileurl><![CDATA[".$_SC['siteurl']."space.php?uid=".$queryuserid."]]></profileurl>";
                       echo "<usergroup id=\"".$userspace['groupid']."\">".$userspace['grouptitle']."</usergroup>"; 
                       echo "<sex>".$genders."</sex>"; 
                       echo "<bday>".$bday."</bday>";
                       echo "<province>".$userspace['resideprovince']."</province>";
                       echo "<city>".$userspace['residecity']."</city>";
                       if($isdetail) {
                            $userspace["name"] = im_xmlsafestr(htmlspecialchars($userspace["name"]));
                            echo "<nick>".$userspace["name"]."</nick>";
                            echo "<email>".$userspace["email"]."</email>";     
                            echo "<credit>".$userspace["credit"]."</credit>";
                       }
                   echo "</userprofile>";
              }
              return true;
	     }else{
              echo "<sessionvalide>false</sessionvalide>";
              return false;
		 }
   }   
   //3-获取用户个人信息，用于显示在聊天窗口中
   function getUserProfile($querysid, $queryuserid, $userkey, $destid, $isdetail){
        global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $im_version, $imxmlperf;
        if(!sitekey_login($queryuserid, $userkey)) {
             return;
        }
        if(!$destid) {
            echo "<error>query destid param not valid</error>";
            return;
        } 
        $queryuserid = intval($queryuserid);
        $destid = intval($destid);
        $isdetail = $isdetail ? ($isdetail=="true" ? 1 : 0): 0;
        $addcoum = '';
        if($isdetail){
             $addcoum = ',s.credit,sf.email';
        }
        $querysql = "SELECT s.uid,s.username,s.name,s.groupid,sf.sex,sf.birthyear,sf.birthmonth,sf.birthday,sf.resideprovince,sf.residecity,u.grouptitle $addcoum FROM ".tname('space')." s
                     LEFT JOIN ".tname('spacefield')." sf ON sf.uid=s.uid
                     LEFT JOIN ".tname('usergroup')." u ON u.gid=s.groupid
                     WHERE s.uid='$destid'";
        $userspace = $_SGLOBAL['db']->fetch_array($_SGLOBAL['db']->query($querysql));
        if(empty($userspace)) {
             echo( "<error>个人空间未开通</error>" );
             return;
        }
        //是否开启实名认证  
        if($_SCONFIG['realname'] && $userspace['name']){ 
           $userspace["username"] = im_xmlsafestr(htmlspecialchars($userspace['name']));
        }else{
             $userspace["username"] = im_xmlsafestr(htmlspecialchars($userspace['username']));
        } 
        $usericon = im_avatar($queryuserid,middle);
        if(empty($_SC['siteurl'])) $_SC['siteurl'] = str_replace(SUB_DIR,'/',getsiteurl());
        $genders = $userspace['sex']==0 ? -1 : ($userspace['sex']==1 ? "male" : "female");
        $bday = sprintf('%04d-%02d-%02d', $userspace['birthyear'], $userspace['birthmonth'], $userspace['birthday']);
        $bday = ($bday=='0000-00-00') ? "" : $bday;   
        echo "<userprofile>";
             echo "<uid>".$destid."</uid>";
             echo "<name>".$userspace["username"]."</name>";
             echo "<nick>".$userspace["name"]."</nick>";
             echo "<icon><![CDATA[".$usericon."]]></icon>";
             echo "<isdefaulticon>-1</isdefaulticon>";
             echo "<profileurl><![CDATA[".$_SC['siteurl']."space.php?uid=".$destid."]]></profileurl>";
             echo "<usergroup id=\"".$userspace['groupid']."\">".$userspace['grouptitle']."</usergroup>"; 
             echo "<sex>".$genders."</sex>"; 
             echo "<bday>".$bday."</bday>";
             echo "<province>".$userspace['resideprovince']."</province>";
             echo "<city>".$userspace['residecity']."</city>";
             if($isdetail) {
                  $userspace["name"] = im_xmlsafestr(htmlspecialchars($userspace["name"]));
                  echo "<nick>".$userspace["name"]."</nick>";
                  echo "<email>".$userspace["email"]."</email>";     
                  echo "<credit>".$userspace["credit"]."</credit>";
             }
        echo "</userprofile>";
   }
    
   //4-获取用户好友列表      
   function getBuddyList($querysid, $queryuserid, $userkey, $pagesize, $pageindex, $isfuidlist, $isdetail, $fuids) {
        global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $imxmlperf, $im_version;
        if(!sitekey_login($queryuserid, $userkey)) {
             return;
        } 
        if(empty($_SC['siteurl'])) $_SC['siteurl'] = str_replace(SUB_DIR,'/',getsiteurl()); 
        $queryuserid = intval($queryuserid);
        $pagesize =  intval($pagesize) > 0 ? intval($pagesize) : 255;
        $pageindex = $pageindex ? intval($pageindex) : 0;     
        $isdetail = $isdetail ? ($isdetail=="true" ? 1 : 0): 0;
        $isfuidlist = $isfuidlist ? (strtolower($isfuidlist)=='true' ? 1 : 0): 0;
        $uidinfo = $_SGLOBAL['db']->fetch_array($_SGLOBAL['db']->query("SELECT s.friendnum,sf.privacy FROM ".tname('space')." s 
                                                LEFT JOIN ".tname('spacefield')." sf ON s.uid=sf.uid WHERE s.uid='$queryuserid'"));
        $buddynum = $uidinfo['friendnum'];
        echo "<pageindex>".$pageindex."</pageindex>";
        echo "<pagesize>".$pagesize."</pagesize>";
        if($fuids && $buddynum){
             $fuids = uid_safecheck($fuids,$buddynum);
        }
        if($isfuidlist || !$fuids){
             echo '<allbuddynum>'.$buddynum.'</allbuddynum>';
        }
        if($isfuidlist){
             echo '<buddyuids>';
        }else{
             echo '<buddylist>';
        }
        if($buddynum){
             $start =  page_start($pageindex, $pagesize, $buddynum);
             $addsql = $addcoum = $groups = $_fuid = '';
             if($pagesize<$buddynum){
                  $addsql = 'ORDER BY f.num DESC, f.dateline DESC';
             }
             if($isfuidlist){
                  $querysql = "SELECT f.fuid FROM ".tname('friend')." f WHERE f.uid='$queryuserid' AND f.status='1' $addsql LIMIT $start, $pagesize";
             }else{
                  if($isdetail){
                       $addcoum = ',s.credit,sf.email';
                  }
                  if($fuids){
                       $querysql = "SELECT s.uid,f.gid,s.username,s.name,sf.friend,sf.sex,sf.birthyear,sf.birthmonth,sf.birthday,sf.resideprovince,sf.residecity $addcoum FROM ".tname('space')." s
                                    LEFT JOIN ".tname('spacefield')." sf ON sf.uid=s.uid
                                    LEFT JOIN ".tname('friend')." f ON f.fuid=s.uid
                                    WHERE s.uid IN ($fuids) AND f.uid='$queryuserid' AND f.status='1'";
                  }else{
                       $querysql = "SELECT s.uid,f.gid,s.username,s.name,sf.friend,sf.sex,sf.birthyear,sf.birthmonth,sf.birthday,sf.resideprovince,sf.residecity $addcoum FROM ".tname('friend')." f
                                    LEFT JOIN ".tname('space')." s ON f.fuid=s.uid
                                    LEFT JOIN ".tname('spacefield')." sf ON sf.uid=s.uid
                                    WHERE f.uid='$queryuserid' AND f.status='1' $addsql LIMIT $start, $pagesize";
                  }
             }
             $query = $_SGLOBAL['db']->query($querysql); 
             while($member = $_SGLOBAL['db']->fetch_array($query)) {
                  if($isfuidlist){
                       $_fuid = $_fuid ? $_fuid.','.$member['fuid'] : $member['fuid'];
                  }else{
                       if($_SCONFIG['realname'] && $member['name']){
                            $member['fusername'] = im_xmlsafestr(htmlspecialchars($member['name']));
                       }else{
                            $member['fusername'] = im_xmlsafestr(htmlspecialchars($member['username']));
                       }
                       $member['usericon'] = im_avatar($member['uid'],middle);
                       $member['gender'] = $member['sex']==0 ? -1 : ($member['sex']==1 ? "male" : "female");
                       $member['bday'] = sprintf('%04d-%02d-%02d', $member['birthyear'], $member['birthmonth'], $member['birthday']);
                       $member['bday'] = ($member['bday']=='0000-00-00') ? "" : $member['bday'];
                       echo "<buddy>";
                            echo "<uid>".$member['uid']."</uid>";
                            echo "<name>".$member['fusername']."</name>";
                            echo "<icon><![CDATA[".$member['usericon']."]]></icon>";
                            echo "<isdefaulticon>-1</isdefaulticon>";
                            echo "<profileurl><![CDATA[".$_SC['siteurl']."space.php?uid=".$member['uid']."]]></profileurl>";
                            //好友组id、名称
                            if($imxmlperf!='high'){
                                 $groups = $groups ? $groups : im_getfriendgroup($uidinfo);
                                 $member['gtitle'] = im_xmlsafestr($groups[$member['gid']]);
                                 echo "<buddygroup id=\"".$member['gid']."\">".$member['gtitle']."</buddygroup>";
                            }
                            echo "<sex>".$member['gender']."</sex>";
                            echo "<bday>".$member['bday']."</bday>";
                            echo "<province>".$member['resideprovince']."</province>";
                            echo "<city>".$member['residecity']."</city>";
                            if($isdetail){
                                 $member["nickname"] = im_xmlsafestr(htmlspecialchars($member["name"]));
                                 echo "<nick>".$member["nickname"]."</nick>";
                                 echo "<credit>".$member["credit"]."</credit>";
                                 echo "<email>".$member["email"]."</email>";
                            }
                       echo "</buddy>";     
                  }
            }   
        }
        if($isfuidlist){
             echo $_fuid;
             echo '</buddyuids>';
        }else{
             echo '</buddylist>';
        } 
   }
 
   //5-添加好友
   function getAddBuddy($querysid, $queryuserid, $userkey, $newbuddyid) {
        global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $im_version;
        if(!sitekey_login($queryuserid, $userkey)) {
             return;
        }
        $newbuddyid = intval($newbuddyid);
        $queryuserid = intval($queryuserid); 
        if($queryuserid == $newbuddyid) {
           echo "<error>不能添加自己为好友</error>";
           echo "<addbuddyresult>failed</addbuddyresult>";
           return ;
        }
        if(!$newbuddyid) {
            echo "<error>无好友可添加</error>" ;
            echo "<addbuddyresult>failed</addbuddyresult>";
            return ;
        }
        if(!checkperm('allowfriend')) {
           echo "<error>无加好友权限</error>";
           echo "<addbuddyresult>failed</addbuddyresult>";
           return ;
        }
        include_once S_ROOT.'./source/function_cp.php';
        if(isblacklist($newbuddyid)) {
            echo "<error>该会员在你的黑名单中</error>";
            echo "<addbuddyresult>failed</addbuddyresult>";
            return ;
        }
        $tospace = getspace_imxml($newbuddyid);
        if(empty($tospace)) {
            echo "<error>用户不存在</error>" ;
            echo "<addbuddyresult>failed</addbuddyresult>";
            return ;
        }
        $fromspace = getspace_imxml($queryuserid);
        $status = getfriendstatus($queryuserid, $newbuddyid);
        if($status == 1) {
            echo "<error>用户已在你的好友列表中</error>";
            echo "<addbuddyresult>failed</addbuddyresult>";
            return ;
        }else{
             $fstatus = getfriendstatus($newbuddyid, $queryuserid);
             if($fstatus == -1) {
                if($status == -1) {
                   $maxfriendnum = checkperm('maxfriendnum');
                   if($maxfriendnum && $space['friendnum'] >= $maxfriendnum) {
                      echo "<error>好友数超过上限</error>";
                      echo "<addbuddyresult>failed</addbuddyresult>";
                      return ;
                   }
                   //添加单向好友
                   $setarr = array(
                          'uid' => $queryuserid,
                          'fuid' => $newbuddyid,
                          'fusername' => addslashes($tospace['username']),
                          'gid' => 0,
                          'note' => "",
                          'dateline' => $_SGLOBAL['timestamp']
                   );
                   inserttable('friend', $setarr);
                   smail($newbuddyid, '', cplang('friend_subject',array(addslashes($tospace['username']))));
                   //发送好友请求
                   echo "<addbuddyresult>confirming</addbuddyresult>";
                   return ;
                }else{
                      //正在等待对方验证
                      echo "<addbuddyresult>confirming</addbuddyresult>";
                      return ;
                }
             }else{
                  //成为好友
                  $gid = 0;
                  friend_update($queryuserid, addslashes($fromspace['username']), $newbuddyid, addslashes($tospace['username']), 'add', $gid);
                  //事件发布
                  $fs = array();
                  $fs['icon'] = 'friend';
                  $fs['title_template'] = cplang('feed_friend_title');
                  $fs['title_data'] = array('touser'=>"<a href=\"space.php?uid=$tospace[uid]\">$tospace[username]</a>");
                  $fs['body_template'] = '';
                  $fs['body_data'] = array();
                  $fs['body_general'] = '';
                  $fromspace['privacy'] = empty($fromspace['privacy'])?(empty($_SCONFIG['privacy'])?array():$_SCONFIG['privacy']):unserialize($fromspace['privacy']);
                   if(!empty($fromspace['privacy']['feed']['friend'])) {
                       $_SGLOBAL['supe_username'] = addslashes($fromspace['username']);
                       $mtime = explode(' ', microtime());
                       $_SGLOBAL['timestamp'] = $mtime[1];
                       feed_add($fs['icon'], $fs['title_template'], $fs['title_data'], $fs['body_template'], $fs['body_data'], $fs['body_general']);
                   }
                  //通知
                  notification_add($newbuddyid, 'friend', cplang('note_friend_add'));
                  //更新uc
                  include_once(S_ROOT.'./uc_client/client.php');
                  uc_friend_add($queryuserid, $newbuddyid);
                  echo "<addbuddyresult>acceptedboth</addbuddyresult>";
                  return ;
             }
        }
   }

   //6-删除好友
   function getDelBuddy ($querysid, $queryuserid, $userkey, $delbuddyid){
         global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $im_version;
         if(!sitekey_login($queryuserid, $userkey)) {
                return;
         }
         if(!$delbuddyid){
             echo "<error>无好友可删除</error>";
             echo "<delbuddyresult>failed</delbuddyresult>";
             return; 
         }
         $delbuddyid = intval($delbuddyid);
         $queryuserid = intval($queryuserid);
         include_once S_ROOT.'./source/function_cp.php'; 
         $query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('space')." WHERE uid=".$delbuddyid);
         if($_SGLOBAL['member'] = $_SGLOBAL['db']->fetch_array($query)) {
            friend_update($queryuserid, '', $delbuddyid, '', 'ignore'); 
            echo "<delbuddyresult>bothsuccess</delbuddyresult>";
            return ;
         }else{
               echo "<error>用户不存在</error>";
               echo "<delbuddyresult>failed</delbuddyresult>";
               return ;
         }            
    }
    
   //7-确认好友请求
   function getConfirmBuddy($querysid, $queryuserid, $userkey, $newbuddyid, $confirm){
        global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $im_version;
        if(!sitekey_login($queryuserid, $userkey)) {
             return;
        }  
        $newbuddyid = intval($newbuddyid);
        $queryuserid = intval($queryuserid); 
        $confirm = trim($confirm);
        include_once S_ROOT.'./source/function_cp.php'; 
        if($confirm == 'accept' || $confirm == 'acceptboth'){
            if($queryuserid == $newbuddyid){
                echo "<error>不能加自己为好友</error>";
                echo "<confirmbuddy>failed</confirmbuddy>";
                return ; 
            } 
            if(!checkperm('allowfriend')) {
                echo "<error>无加好友权限</error>";
                echo "<confirmbuddy>failed</confirmbuddy>";
                return ;
            }
            $tospace = getspace_imxml($newbuddyid);
            if(empty($tospace)) {
                echo "<error>用户不存在</error>" ;
                echo "<addbuddyresult>failed</addbuddyresult>";
                return ;
            }
            $status = getfriendstatus($newbuddyid, $queryuserid);
            if($status == 1) {
                echo "<error>该用户已经是你好友</error>";
                echo "<confirmbuddy>failed</confirmbuddy>";
                return ; 
            }elseif($status == 0){
                   $gid = 0;
                   $fromspace = getspace_imxml($queryuserid);  
                   friend_update($queryuserid, addslashes($fromspace['username']), $newbuddyid, addslashes($tospace['username']), 'add', $gid);
                   //加好友发布事件
                   $fs = array();
                   $fs['icon'] = 'friend';
                   $fs['title_template'] = cplang('feed_friend_title');
                   $fs['title_data'] = array('touser'=>"<a href=\"space.php?uid=$tospace[uid]\">".$_SN[$tospace['uid']]."</a>");
                   $fs['body_template'] = '';
                   $fs['body_data'] = array();
                   $fs['body_general'] = '';
                   $fromspace['privacy'] = empty($fromspace['privacy'])?(empty($_SCONFIG['privacy'])?array():$_SCONFIG['privacy']):unserialize($fromspace['privacy']);
                   if(!empty($fromspace['privacy']['feed']['friend'])) {
                       $_SGLOBAL['supe_username'] = addslashes($fromspace['username']);
                       feed_add($fs['icon'], $fs['title_template'], $fs['title_data'], $fs['body_template'], $fs['body_data'], $fs['body_general']);
                   }
                   //通知
                   notification_add($newbuddyid, 'friend', cplang('note_friend_add'));
                   //更新uc
                   include_once(S_ROOT.'./uc_client/client.php');
                   uc_friend_add($queryuserid, $newbuddyid); 
                   echo "<confirmbuddy>acceptedboth</confirmbuddy>";
                   return ; 
            }else{
                  echo "<error>无加好友请求可处理</error>";
                  echo "<confirmbuddy>failed</confirmbuddy>";
            }       
        }elseif($confirm == 'refuse'){
               friend_update($queryuserid, '', $newbuddyid, '', 'ignore');
               echo "<confirmbuddy>refused</confirmbuddy>";
        }else{
             echo "<error>无效的确认请求</error>";
             echo "<confirmbuddy>failed</confirmbuddy>";
        }
   }
   
   //8- 查询在线聊友的最近动态
   function getUserActivity($querysid, $queryuserid, $userkey, $destid, $time, $maxnum){
        global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $im_version;
        if(!sitekey_login($queryuserid, $userkey)) {
             return;
        }
        if(!$destid) {
            echo "<error>query destid param not valid</error>";
            return ;
        }
        if(empty($_SC['siteurl'])) $_SC['siteurl'] = str_replace(SUB_DIR,'/',getsiteurl());
        $queryuserid = intval($queryuserid);
        $destid = intval($destid);
        $querytime = $time ? $_SGLOBAL['timestamp']-intval($time) : $_SGLOBAL['timestamp']-3600*24*3;
        $maxnum = intval($maxnum) > 0 ? intval($maxnum) : 10;
        //为了提升性能，取动态时，获取指定时间之后2倍 $maxnum数目的记录，然后再倒序获取30条
        $limnum = $maxnum * 2;
        $uchappid =  UC_APPID;
        $useractivity = array();
        $query = $_SGLOBAL['db']->query("SELECT f.*,s.name,s.namestatus FROM ".tname('feed')." f,".tname('space')." s
                 WHERE f.uid=s.uid AND f.uid='$destid' AND f.dateline>='$querytime' AND f.appid='$uchappid' ORDER BY f.dateline DESC LIMIT 0,$limnum");
        while($value = $_SGLOBAL['db']->fetch_array($query)){
              //有效动态数不超过$maxnum条
              if(count($useractivity) > $maxnum){   
                  break;
              }
              $imtype = imactivitytype($value['icon']);
              //排除非获取类型的动态，以及创建相册动态
              if($imtype[0]>1 || ($imtype[0]==1 && $value['image_1'])){
                  $uid = $value['uid'];
                  $value['profileurl'] = $_SC['siteurl']."space.php?uid=".$uid;
                  $value["username"] = ($_SCONFIG['realname'] && $value['namestatus']) ? $value['name'] : $value['username'];
                  $value["username"] = im_xmlsafestr(htmlspecialchars($value["username"]));
                  $value['usericon'] = im_avatar($uid,middle,true);
                  $value = mkfeed($value);
                  $value['type'] = $imtype[1];
                  $value['image'] = $value['image_1'] ? $_SC['siteurl'].$value['image_1'] : '';
                  if($imtype[0]==5){
                     //处理加为好友（合并记录）
                     $value['title'] = ''; 
                     $value['url'] = $value['profileurl']; 
                     if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['title_data']['touser'],$matches)){
                         $friendname = im_xmlsafestr($matches[2]);     
                         $friendcontent .= "<user url=\"".$_SC['siteurl'].$matches[1]."\">".$friendname."</user>";     
                     }
                     $value['content'] = $friendcontent;
                     $useractivity['f'] = $value;
                     continue;
                  }elseif($imtype[0]==1){
                      //处理上传照片
                      $value['title'] = '';
                      if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['body_data']['album'],$matches)){
                          $value['content'] = "<album url=\"".$_SC['siteurl'].$matches[1]."\">".$matches[2]."</album>";
                          $value['content'] = im_filtstr($value['content']);
                          $value['content'] .= "<image url=\"".$_SC['siteurl'].$value['image_1_link']."\">".$_SC['siteurl'].$value['image_1']."</image>";
                          $value['content'] .= $value['image_2'] ? "<image url=\"".$_SC['siteurl'].$value['image_2_link']."\">".$_SC['siteurl'].$value['image_2']."</image>" : '';
                          $value['content'] .= $value['image_3'] ? "<image url=\"".$_SC['siteurl'].$value['image_3_link']."\">".$_SC['siteurl'].$value['image_3']."</image>" : ''; 
                          $value['content'] .= $value['image_4'] ? "<image url=\"".$_SC['siteurl'].$value['image_4_link']."\">".$_SC['siteurl'].$value['image_4']."</image>" : ''; 
                          $value['url'] = $_SC['siteurl'].$matches[1];
                       }
                  }elseif($imtype[0]==2){
                       //处理加入群组、记录道
                       $value['title'] = '';
                       if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['title_data']['mtag'],$matches)){
                           $value['content'] = "<group url=\"".$_SC['siteurl'].$matches[1]."\">".$matches[2]."</group>"; 
                           $value['content'] = im_filtstr($value['content']);
                           $value['url'] = $_SC['siteurl'].$matches[1]; 
                       }else{
                           $value['content'] = trim(getstr(im_filtstr($value['title_data']['message']),80,0,0,0,0,-1));
                           $value['url'] = $_SC['siteurl']."space.php?uid=".$uid."&do=doing&doid=".$value['body_data']['doid']; 
                       }
                  }elseif($imtype[0]==3){
                       //处理发表日志和发起话题（获取群组名称）
                       $value['title'] = trim(getstr(im_filtstr($value['body_data']['subject']),80,0,0,0,0,-1)); 
                       if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['body_data']['mtag'],$matches)){
                           $value['content'] = "<group url=\"".$_SC['siteurl'].$matches[1]."\">".$matches[2]."</group>";
                       }else{
                            $value['content'] = "";
                       }
                       $value['content'] .= trim((getstr(im_filtstr($value['body_data']['summary']),80,0,0,0,0,-1)));
                       if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['body_data']['subject'],$match)){
                          $value['url'] = $_SC['siteurl'].$match[1]; 
                       }
                  }elseif($imtype[0]==4){
                       //处理发表回复（话题的title）、评论了（日志的title）
                       if($value['title_data']['thread']){
                           $value['title'] = trim(getstr(im_filtstr($value['title_data']['thread']),80,0,0,0,0,-1));
                       }else{
                             $value['title'] = trim(getstr(im_filtstr($value['title_data']['blog']),80,0,0,0,0,-1));
                       }
                       if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['title_data']['touser'],$matches)){
                           $value['content'] = "<user url=\"".$_SC['siteurl'].$matches[1]."\">".$matches[2]."</user>"; 
                           $value['content'] = im_xmlsafestr($value['content']);     
                       } 
                       if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['title_data']['thread'],$match)){
                           $value['url'] = $_SC['siteurl'].$match[1]; 
                       }elseif(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['title_data']['blog'],$match)){
                           $value['url'] = $_SC['siteurl'].$match[1]; 
                       }
                  }
                  $useractivity[] = $value;
              } 
           }
           echo "<useractivity>";
           foreach($useractivity AS $activity){
                echo "<activity>";
                   echo "<user uid=\"".$activity['uid']."\" url=\"".$activity['profileurl']."\">".$activity["username"]."</user>";
                   echo "<icon><![CDATA[".$activity["usericon"]."]]></icon>";
                   echo "<isdefaulticon>-1</isdefaulticon>";
                   echo "<type>".$activity['type']."</type>"; 
                   echo "<title><![CDATA[".$activity['title']."]]></title>"; 
                   echo "<content><![CDATA[".$activity['content']."]]></content>";
                   echo "<time>".$activity['dateline']."</time>";
                   echo "<url><![CDATA[".$activity['url']."]]></url>";  
                   echo "<image><![CDATA[".$activity['image']."]]></image>";
                echo "</activity>";
           }               
        echo "</useractivity>";
   }
   
   //9- 查询所有好友的最近动态
   function getBuddylistActivity($querysid, $queryuserid, $userkey, $time, $maxnum, $pagesize, $pageindex, $fuids){
        global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $im_version;
        if(!sitekey_login($queryuserid, $userkey)) {
             return;
        }
        $queryuserid = intval($queryuserid);
        $pagesize =  intval($pagesize) > 0 ? intval($pagesize) : 255;
        $pageindex = $pageindex ? intval($pageindex) : 0;
        $querytime = $time ? $_SGLOBAL['timestamp']-intval($time) : $_SGLOBAL['timestamp']-3600*24*3;
        $maxnum = intval($maxnum) > 0 ? intval($maxnum) : 30;
        //为了提升性能，取动态时，获取指定时间之后3倍 $maxnum数目的记录，然后再倒序获取30条
        $limnum = $maxnum * 3; 
        $uchappid =  UC_APPID;
        $buddynum = $_SGLOBAL['db']->result($_SGLOBAL['db']->query("SELECT friendnum FROM ".tname('space')." WHERE uid='$queryuserid'"), 0);
        echo "<pageindex>".$pageindex."</pageindex>";
        echo "<pagesize>".$pagesize."</pagesize>";
        if($fuids && $buddynum){
             $fuids = uid_safecheck($fuids,$buddynum);
        }
        if(!$fuids){
             echo '<allbuddynum>'.$buddynum.'</allbuddynum>';
        }
        echo "<buddylistactivity>"; 
        if($buddynum){
        	if(empty($_SC['siteurl'])) $_SC['siteurl'] = str_replace(SUB_DIR,'/',getsiteurl());
            $buddynew = $buddyactivity = $postlist = $friends = array();
            $anum = $fnum = 0;
            if(!$fuids){
                 $start =  page_start($pageindex, $pagesize, $buddynum);
                 $fuids = "SELECT fuid FROM (SELECT fuid FROM ".tname('friend')." WHERE uid='$queryuserid' AND status='1' LIMIT $start, $pagesize) as fr";
            }
            $query = $_SGLOBAL['db']->query("SELECT * FROM (SELECT f.*,s.name,s.namestatus 
                          FROM  ".tname('feed')." f 
                          LEFT JOIN ".tname('space')." s ON f.uid=s.uid
                          WHERE f.uid IN ($fuids) AND f.dateline>='$querytime' AND f.appid='$uchappid' LIMIT 0,$limnum)
                          AS tt ORDER BY tt.dateline DESC");
            while($value = $_SGLOBAL['db']->fetch_array($query)){
                  //所有好友动态不超过maxnum
                  if($anum+$fnum > $maxnum){   
                      break;
                  }
                  //单个好友动态不超过5条
                  $uid = $value['uid']; 
                  if(count($postlist[$uid])>5){
                     continue;
                  } 
                  $imtype = imactivitytype($value['icon']); 
                  //排除非获取类型的动态，以及创建相册动态
                  if($imtype[0]>1 || ($imtype[0]==1 && $value['image_1'])){
                      $uid = $value['uid'];
                      $value['profileurl'] = $_SC['siteurl']."space.php?uid=".$uid;
                      $value["username"] = ($_SCONFIG['realname'] && $value['namestatus']) ? $value['name'] : $value['username'];
                      $value["username"] = im_xmlsafestr(htmlspecialchars($value["username"]));
                      $value['usericon'] = im_avatar($uid,middle,true);
                      $value = mkfeed($value);
                      $value['type'] = $imtype[1];
                      $value['image'] = $value['image_1'] ? $_SC['siteurl'].$value['image_1'] : '';
                      if($imtype[0]==5){
                         //处理加为好友（合并记录）
                         $value['title'] = ''; 
                         $value['url'] = $value['profileurl']; 
                         if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['title_data']['touser'],$matches)){
                             $value['friendname'] = im_xmlsafestr($matches[2]);
                             $friends[$uid]['content'] .= "<user url=".$_SC['siteurl'].$matches[1].">".$value['friendname']."<user>";
                         }
                         $value['content'] = $friends[$uid]['content'];
                         $postlist[$uid]['f'] = $value;
                         $buddyactivity['f'][$uid] = $value;
                         $fnum = count($buddyactivity['f']);
                         continue;
                      }elseif($imtype[0]==1){
                           //处理上传照片
                           $value['title'] = '';
                           if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['body_data']['album'],$matches)){
                               $value['content'] = "<album url=\"".$_SC['siteurl'].$matches[1]."\">".$matches[2]."</album>";
                               $value['content'] = im_filtstr($value['content']);
                               $value['content'] .= "<image url=\"".$_SC['siteurl'].$value['image_1_link']."\">".$_SC['siteurl'].$value['image_1']."</image>";
                               $value['content'] .= $value['image_2'] ? "<image url=\"".$_SC['siteurl'].$value['image_2_link']."\">".$_SC['siteurl'].$value['image_2']."</image>" : '';
                               $value['content'] .= $value['image_3'] ? "<image url=\"".$_SC['siteurl'].$value['image_3_link']."\">".$_SC['siteurl'].$value['image_3']."</image>" : ''; 
                               $value['content'] .= $value['image_4'] ? "<image url=\"".$_SC['siteurl'].$value['image_4_link']."\">".$_SC['siteurl'].$value['image_4']."</image>" : ''; 
                               $value['url'] = $_SC['siteurl'].$matches[1];
                           }
                      }elseif($imtype[0]==2){
                           //处理加入群组、记录道
                           $value['title'] = '';
                           if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['title_data']['mtag'],$matches)){
                               $value['content'] = "<group url=\"".$_SC['siteurl'].$matches[1]."\">".$matches[2]."</group>"; 
                               $value['content'] = im_filtstr($value['content']);
                               $value['url'] = $_SC['siteurl'].$matches[1]; 
                           }else{
                               $value['content'] = trim(getstr(im_filtstr($value['title_data']['message']),80,0,0,0,0,-1));
                               $value['url'] = $_SC['siteurl']."space.php?uid=".$uid."&do=doing&doid=".$value['body_data']['doid']; 
                           }
                      }elseif($imtype[0]==3){
                           //处理发表日志和发起话题（获取群组名称）
                           $value['title'] = trim(getstr(im_filtstr($value['body_data']['subject']),80,0,0,0,0,-1)); 
                           if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['body_data']['mtag'],$matches)){
                               $value['content'] = "<group url=\"".$_SC['siteurl'].$matches[1]."\">".$matches[2]."</group>";
                           }else{
                                $value['content'] = "";
                           }
                           $value['content'] .= trim(getstr(im_filtstr($value['body_data']['summary']),80,0,0,0,0,-1));
                           if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['body_data']['subject'],$match)){
                              $value['url'] = $_SC['siteurl'].$match[1]; 
                           }
                      }elseif($imtype[0]==4){
                           //处理发表回复（话题的title）、评论了（日志的title）
                           if($value['title_data']['thread']){
                               $value['title'] = trim(getstr(im_filtstr($value['title_data']['thread']),80,0,0,0,0,-1));
                           }else{
                                 $value['title'] = trim(getstr(im_filtstr($value['title_data']['blog']),80,0,0,0,0,-1));
                           }
                           if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['title_data']['touser'],$matches)){
                               $value['content'] = "<user url=\"".$_SC['siteurl'].$matches[1]."\">".$matches[2]."</user>"; 
                               $value['content'] = im_xmlsafestr($value['content']);     
                           } 
                           if(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['title_data']['thread'],$match)){
                               $value['url'] = $_SC['siteurl'].$match[1]; 
                           }elseif(preg_match("/<a.?href=\"(.*)\">(.*)<\/a>/i",$value['title_data']['blog'],$match)){
                               $value['url'] = $_SC['siteurl'].$match[1]; 
                           }
                      }
                      $postlist[$uid][] = $value;
                      $buddyactivity['a'][] = $value;
                      $anum = count($buddyactivity['a']);
                  }else{
                        continue;
                  }
            }
            foreach($buddyactivity AS $newactivity){
                 if(is_array($newactivity)){
                      foreach($newactivity AS $activity){
                           echo "<activity>";
                                echo "<user uid=\"".$activity['uid']."\" url=\"".$activity['profileurl']."\">".$activity["username"]."</user>";
                                echo "<icon><![CDATA[".$activity["usericon"]."]]></icon>";
                                echo "<isdefaulticon>-1</isdefaulticon>";
                                echo "<type>".$activity['type']."</type>"; 
                                echo "<title><![CDATA[".$activity['title']."]]></title>"; 
                                echo "<content><![CDATA[".$activity['content']."]]></content>";
                                echo "<time>".$activity['dateline']."</time>";
                                echo "<url><![CDATA[".$activity['url']."]]></url>";  
                                echo "<image><![CDATA[".$activity['image']."]]></image>";
                           echo "</activity>";
                      }
                 }
            }  
        }
        echo "</buddylistactivity>";
   }
   
   //10- 查询网站的最近动态
   function getSiteActivity($querysid, $queryuserid, $userkey, $newtime,$hottime, $maxnum){
        global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $im_version;
        if(!sitekey_login($queryuserid, $userkey)) {
             return;
        }
        if(empty($_SC['siteurl'])) $_SC['siteurl'] = str_replace(SUB_DIR,'/',getsiteurl()); 
        $queryuserid = intval($queryuserid);
        $querynewtime = $newtime ? $_SGLOBAL['timestamp']-intval($newtime) : $_SGLOBAL['timestamp']-3600*24*30;
        $queryhottime = $hottime ? $_SGLOBAL['timestamp']-intval($hottime) : $_SGLOBAL['timestamp']-3600*24;
        $maxnum = intval($maxnum) > 0 ? intval($maxnum) : 30;
        echo "<siteactivity>";
        //按照发表时间对日志和话题进行排序，各取maxnum条
        echo "<newactivity>";
        $newactivity = array();
        $query = $_SGLOBAL['db']->query("SELECT b.blogid,b.uid,b.username,b.subject,b.dateline,b.pic,b.picflag,b.viewnum,b.replynum,bf.message,s.name,s.namestatus FROM ".tname('blog')." b
                 LEFT JOIN ".tname('blogfield')." bf ON b.blogid=bf.blogid
                 LEFT JOIN ".tname('space')." s ON s.uid=b.uid
                 WHERE b.friend='0' ORDER BY b.dateline DESC LIMIT 0,$maxnum");
        while($newvalue = $_SGLOBAL['db']->fetch_array($query)){
               $uid = $newvalue['uid'];
               $newvalue['profileurl'] = $_SC['siteurl']."space.php?uid=".$uid;
               $newvalue['username'] = ($_SCONFIG['realname'] && $newvalue['namestatus']) ? $newvalue['name'] : $newvalue['username'];
               $newvalue['username'] = im_xmlsafestr(htmlspecialchars($newvalue['username']));
               $newvalue['usericon'] = im_avatar($uid,middle,true);               
               $newvalue['type'] = "发表日志"; 
               //以下是截取标题和内容的前80个字符 ，并还原用户可能输入的一些特殊字符 
               $newvalue['title'] = trim(getstr(im_filtstr($newvalue['subject']),80,1,0,0,0,-1));
               $newvalue['content'] = trim(getstr(im_filtstr($newvalue['message']),80,1,0,0,0,-1));
               
               $newvalue['time'] = $newvalue['dateline'];   
               $newvalue['url'] =  $_SC['siteurl']."space.php?uid=".$newvalue['uid']."&do=blog&id=".$newvalue['blogid'];
               $newvalue['image'] = $newvalue['pic'] ? $_SC['siteurl'].im_mkpicurl($newvalue):''; 
               $newactivity[] = $newvalue;
        }
        $query = $_SGLOBAL['db']->query("SELECT t.tid,t.uid,t.username,t.subject,t.dateline,t.viewnum,t.replynum,p.pic,p.message,s.name,s.namestatus FROM ".tname('thread')." t
                 LEFT JOIN ".tname('post')." p ON t.tid=p.tid and p.isthread='1'
                 LEFT JOIN ".tname('mtag')." m ON m.tagid=t.tagid AND m.viewperm='0'
                 LEFT JOIN ".tname('space')." s ON s.uid=t.uid 
                 ORDER BY t.tid DESC LIMIT 0,$maxnum");
        while($newthread = $_SGLOBAL['db']->fetch_array($query)){
               $uid = $newthread['uid'];
               $newthread['profileurl'] = $_SC['siteurl']."space.php?uid=".$uid; 
               $newthread['username'] = ($_SCONFIG['realname'] && $newthread['namestatus']) ? $newthread['name'] : $newthread['username'];
               $newthread['username'] = im_xmlsafestr(htmlspecialchars($newthread['username']));
               $newthread['usericon'] = im_avatar($uid,middle,true);               
               $newthread['type'] = "发起话题";  
               //以下是截取标题和内容的前80个字符 ，并还原用户可能输入的一些特殊字符 
               $newthread['title'] = trim(getstr(im_filtstr($newthread['subject']),80,1,0,0,0,-1));
               $newthread['content'] = trim(getstr(im_filtstr($newthread['message']),80,1,0,0,0,-1));
               //获取内容中的第一张图片
               if(preg_match("/<IMG.*file=\"(.*)\"*?>/i",$newthread['message'],$matches)){
                       $newthread['image'] = $_SC['siteurl'].$matches[1]; 
               }else{
                    $newthread['image'] = "";
               }
               $newthread['time'] = $newthread['dateline'];   
               $newthread['url'] =  $_SC['siteurl']."space.php?uid=".$newthread['uid']."&do=thread&id=".$newthread['tid'];
               $newactivity[] = $newthread;
        }
        $tempacts1 = $tempacts2 = $tempacts3 = $tempacts = array();
        //按照发布时间排序
        foreach($newactivity AS $k=> $tacts){
                  $tempacts1[$k] = $tacts['time'];
        }
        array_multisort($tempacts1, SORT_DESC,$newactivity);
        //按照浏览数排序
        foreach($newactivity AS $m => $tempriority){
               $newactivity[$m]['priority1'] = 60 - intval($m);
               $tempacts2[$m] = $tempriority['pageviews'];
        }
        array_multisort($tempacts2,SORT_DESC,$tempacts1,SORT_DESC,$newactivity);
        //按照回复数/评论数排序
        foreach($newactivity AS $m => $tempriority){
               $newactivity[$m]['priority2'] = 60 - intval($m);
               $tempacts3[$m] = $tempriority['comments']; 
        }
        array_multisort($tempacts3,SORT_DESC,$tempacts2,SORT_DESC,$tempacts1,SORT_DESC,$newactivity);
        //按照综合情况排序
        foreach($newactivity AS $m => $tempriority){
               $tempacts[$m] = 3*$tempriority['priority1'] + 2*$tempriority['priority2'] + 60 - intval($m);
        }
        array_multisort($tempacts,SORT_DESC, $tempacts1,SORT_DESC,$newactivity);
        foreach($newactivity AS $newlist){
                 echo "<activity>";
                   echo "<user uid=\"".$newlist['uid']."\" url=\"".$newlist['profileurl']."\">".$newlist["username"]."</user>";
                   echo "<icon><![CDATA[".$newlist["usericon"]."]]></icon>";
                   echo "<isdefaulticon>-1</isdefaulticon>";
                   echo "<type>".$newlist['type']."</type>"; 
                   echo "<title><![CDATA[".$newlist['title']."]]></title>"; 
                   echo "<content><![CDATA[".$newlist['content']."]]></content>";
                   echo "<time>".$newlist['dateline']."</time>";
                   echo "<url><![CDATA[".$newlist['url']."]]></url>";  
                   echo "<image><![CDATA[".$newlist['image']."]]></image>";
                   echo "<pageviews>".$newlist['viewnum']."</pageviews>";
                   echo "<comments>".$newlist['replynum']."</comments>";
                 echo "</activity>";     
        }           
        echo "</newactivity>";
        //按照pv对日志和话题进行排序，各取maxnum条
        echo "<hotactivity>";
        $hotactivity = array();
        $query = $_SGLOBAL['db']->query("SELECT b.blogid,b.uid,b.username,b.subject,b.dateline,b.pic,b.picflag,b.viewnum,b.replynum,bf.message,s.name,s.namestatus FROM ".tname('blog')." b
                 LEFT JOIN ".tname('blogfield')." bf ON b.blogid=bf.blogid
                 LEFT JOIN ".tname('space')." s ON s.uid=b.uid
                 WHERE b.friend='0' AND b.dateline>'$queryhottime' ORDER BY b.dateline DESC LIMIT 0,$maxnum");
        while($hotvalue = $_SGLOBAL['db']->fetch_array($query)){
               $uid = $hotvalue['uid'];
               $hotvalue['profileurl'] = $_SC['siteurl']."space.php?uid=".$uid; 
               $hotvalue['username'] = ($_SCONFIG['realname'] && $hotvalue['namestatus']) ? $hotvalue['name'] : $hotvalue['username'];
               $hotvalue['username'] = im_xmlsafestr(htmlspecialchars($hotvalue['username']));
               $hotvalue['usericon'] = im_avatar($uid,middle,true);              
               $hotvalue['type'] = "发表日志";
               //以下是截取标题和内容的前80个字符 ，并还原用户可能输入的一些特殊字符 
               $hotvalue['title'] = trim(getstr(im_filtstr($hotvalue['subject']),80,1,0,0,0,-1));
               $hotvalue['content'] = trim(getstr(im_filtstr($hotvalue['message']),80,1,0,0,0,-1));
               
               $hotvalue['time'] = $hotvalue['dateline'];   
               $hotvalue['url'] =  $_SC['siteurl']."space.php?uid=".$hotvalue['uid']."&do=blog&id=".$hotvalue['blogid'];
               $hotvalue['image'] = $hotvalue['pic'] ? $_SC['siteurl'].im_mkpicurl($hotvalue):''; 
               $hotactivity[] = $hotvalue;
        }
        $query = $_SGLOBAL['db']->query("SELECT t.tid,t.uid,t.username,t.subject,t.dateline,t.viewnum,t.replynum,p.pic,p.message,s.name,s.namestatus FROM ".tname('thread')." t
                 LEFT JOIN ".tname('post')." p ON t.tid=p.tid AND p.isthread='1'
                 LEFT JOIN ".tname('mtag')." m ON m.tagid=t.tagid AND m.viewperm='0'
                 LEFT JOIN ".tname('space')." s ON s.uid=t.uid
                 WHERE t.dateline>'$queryhottime' ORDER BY t.tid DESC LIMIT 0,$maxnum");
        while($hotthread = $_SGLOBAL['db']->fetch_array($query)){
               $uid = $hotthread['uid'];
               $hotthread['profileurl'] = $_SC['siteurl']."space.php?uid=".$uid; 
               $hotthread['username'] = ($_SCONFIG['realname'] && $hotthread['namestatus']) ? $hotthread['name'] : $hotthread['username'];
               $hotthread['username'] = im_xmlsafestr(htmlspecialchars($hotthread['username']));
               $hotthread['usericon'] = im_avatar($uid,middle,true);               
               $hotthread['type'] = "发起话题";
               //以下是截取标题和内容的前80个字符 ，并还原用户可能输入的一些特殊字符 
               $hotthread['title'] = trim(getstr(im_filtstr($hotthread['subject']),80,1,0,0,0,-1));
               $hotthread['content'] = trim(getstr(im_filtstr($hotthread['message']),80,1,0,0,0,-1));
               
               //获取内容中的第一张图片
               if(preg_match("/<IMG.*file=\"(.*)\"*?>/i",$hotthread['message'],$matche)){
                   $hotthread['image'] = $_SC['siteurl'].$matche[1]; 
               }else{
                    $hotthread['image'] = "";
               }
               $hotthread['time'] = $hotthread['dateline'];   
               $hotthread['url'] =  $_SC['siteurl']."space.php?uid=".$hotthread['uid']."&do=thread&id=".$hotthread['tid'];
               $hotactivity[] = $hotthread;
        }      
        $tempacts1 = $tempacts2 = $tempacts = array();
        //按照浏览数排序
        foreach($hotactivity AS $k=> $tacts){
                  $tempacts1[$k] = $tacts['pageviews'];
        }
        array_multisort($tempacts1, SORT_DESC,$hotactivity);
        //按照回复数/评论数排序
        foreach($hotactivity AS $m => $tempriority){
               $hotactivity[$m]['priority'] = 60 - intval($m);
               $tempacts2[$m] = $tempriority['comments'];
        }
        array_multisort($tempacts2,SORT_DESC,$tempacts1,SORT_DESC,$hotactivity);
        //按照综合情况排序
        foreach($hotactivity AS $m => $tempriority){
                $tempacts[$m] = 2*$tempriority['priority'] + 60 - intval($m); 
        }
        array_multisort($tempacts,SORT_DESC, $tempacts1,SORT_DESC,$hotactivity);
        foreach($hotactivity AS $hotlist){
                 echo "<activity>";
                   echo "<user uid=\"".$hotlist['uid']."\" url=\"".$hotlist['profileurl']."\">".$hotlist["username"]."</user>";
                   echo "<icon><![CDATA[".$hotlist["usericon"]."]]></icon>";
                   echo "<isdefaulticon>-1</isdefaulticon>"; 
                   echo "<type>".$hotlist['type']."</type>"; 
                   echo "<title><![CDATA[".$hotlist['title']."]]></title>"; 
                   echo "<content><![CDATA[".$hotlist['content']."]]></content>";
                   echo "<time>".$hotlist['dateline']."</time>";
                   echo "<url><![CDATA[".$hotlist['url']."]]></url>";  
                   echo "<image><![CDATA[".$hotlist['image']."]]></image>";
                   echo "<pageviews>".$hotlist['viewnum']."</pageviews>";
                   echo "<comments>".$hotlist['replynum']."</comments>";
                 echo "</activity>";   
        }           
        echo "</hotactivity>";
        echo "</siteactivity>";  
   }

   //12- 我的空间访客列表
   function getVisitorlist($querysid, $queryuserid, $userkey, $maxnum){
        global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $im_version, $imxmlperf;
        if(!sitekey_login($queryuserid, $userkey)) {
             return;
        }
        $queryuserid = intval($queryuserid);  
        $maxnum = intval($maxnum) > 0 ? intval($maxnum) : 30;
        $query = $_SGLOBAL['db']->query("SELECT s.name,s.username, v.* FROM ".tname('visitor')." v, ".tname('space')." s
                 WHERE s.uid=v.vuid AND v.uid='$queryuserid' ORDER BY v.dateline DESC LIMIT 0,$maxnum");
        echo "<visitorlist>";
        while($value = $_SGLOBAL['db']->fetch_array($query)){
               //是否开启实名认证  
               if($_SCONFIG['realname'] && $userspace['name']){ 
                   $value["username"] = im_xmlsafestr(htmlspecialchars($value['name']));
               }else{
                   $value["username"] = im_xmlsafestr(htmlspecialchars($value['username']));
               }
               $value['usericon'] = im_avatar($value['vuid'],middle);
               if(empty($_SC['siteurl'])) $_SC['siteurl'] = str_replace(SUB_DIR,'/',getsiteurl());
               echo "<visitor>";
                 echo "<uid>".$value['vuid']."</uid>";
                 echo "<name>".$value['username']."</name>";
                 echo "<icon><![CDATA[".$value['usericon']."]]></icon>";
                 echo "<isdefaulticon>-1</isdefaulticon>";
                 echo "<profileurl><![CDATA[".$_SC['siteurl']."space.php?uid=".$value['vuid']."]]></profileurl>"; 
               echo "</visitor>";
        }
        echo "</visitorlist>";
   }

   //13- 将用户在IM上积分转换为网站积分 
   function getNotifyImAction($queryuserid, $userkey, $actionid, $moneyrate, $actionmoney){
       
   }

   //14-获取网站相关WDK配置
   function getSiteProfile(){
        global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $imversion, $imbuild;
        echo "<software>uchome</software>";
        echo "<softwareversion>".X_VER."</softwareversion>";
        echo "<language>".$_SC['charset']."</language>";
        echo "<isusesitekey>true</isusesitekey>";
        echo "<systimestamp>".$_SGLOBAL['timestamp']."</systimestamp>";
        echo "<sitename>".$_SCONFIG['sitename']."</sitename>";
        echo "<version>".$imversion."</version>";
        echo "<build>".$imbuild."</build>";
        echo '<groupchatmsgtothread>false</groupchatmsgtothread>';
        echo '<mycenter>false</mycenter>';
        echo '<sitefocus>false</sitefocus>';
        echo '<sitehavegroup>true</sitehavegroup>';  
   }

   //15-返回用户加入的群信息
   function getMyGroup($querysid, $queryuserid, $userkey, $maxnum){
         global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $imversion;
         if(!sitekey_login($queryuserid, $userkey)) {
              return;
         }
         $queryuserid = intval($queryuserid);
         $maxnum = intval($maxnum) > 0 ? intval($maxnum) : 100;
         $query = $_SGLOBAL['db']->query("SELECT t.tagid,m.tagname,m.membernum,m.announcement,m.pic,m.viewperm 
         	 	  FROM (SELECT tagid FROM ".tname('tagspace')." WHERE  uid='$queryuserid' AND grade!='-2' LIMIT 0,$maxnum) t
                  LEFT JOIN ".tname('mtag')." m ON t.tagid=m.tagid"); 
         echo "<grouplist>"; 
         while($value = $_SGLOBAL['db']->fetch_array($query)){
              $gname = im_filtstr($value['tagname']);
              $notice = im_filtstr($value['announcement']);
              echo "<groupprofile>"; 
              echo "<gid>".$value['tagid']."</gid>";
              echo "<gname><![CDATA[".$gname."]]></gname>";
              echo "<headurl><![CDATA[".$value['pic']."]]></headurl>";
              echo "<notice><![CDATA[".$notice."]]></notice>";
              echo "</groupprofile>";
         }
         echo "</grouplist>";
   }      
   //16-返回群成员列表
    function getGroupMemberlist($gid, $groupkey, $pagesize, $pageindex, $queryuserid){
         global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $imxmlperf, $imversion;
         if(!groupkey_login($gid,$groupkey)){
             return;
         }
         $gid = intval($gid);
         $queryuserid = intval($queryuserid);
         if(empty($_SC['siteurl'])) $_SC['siteurl'] = str_replace(SUB_DIR,'/',getsiteurl()); 
         if($queryuserid){
             $query = $_SGLOBAL['db']->query("SELECT t.grade,s.uid,s.username,s.name,s.avatar,sf.sex,sf.birthyear,sf.birthmonth,sf.birthday,sf.resideprovince,sf.residecity FROM ".tname('tagspace')." t
                      LEFT JOIN ".tname('space')." s ON t.uid=s.uid
                      LEFT JOIN ".tname('spacefield')." sf ON sf.uid=s.uid
                      WHERE t.tagid='$gid' AND t.uid='$queryuserid' AND t.grade!='-2'");
              if($value = $_SGLOBAL['db']->fetch_array($query)){
                   //是否开启实名认证  
                  if($_SCONFIG['realname'] && $value['name']){ 
                     $value["username"] = im_xmlsafestr(htmlspecialchars($value['name']));
                  }else{
                     $value["username"] = im_xmlsafestr(htmlspecialchars($value['username']));
                  }
                  $usericon = im_avatar($value['uid'],middle); 
                  $genders = $value['sex']==0 ? -1 : ($value['sex']==1 ? "male" : "female");
                  $bday = sprintf('%04d-%02d-%02d', $value['birthyear'], $value['birthmonth'], $value['birthday']);
                  $bday = ($bday=='0000-00-00') ? "" : $bday;
                  //2：（创建人）；3：（管理员）；4：（普通用户）；10：（禁言） 
                  $level = ($value['grade']==9) ? 2 :($value['grade']==8 ? 3 :($value['grade']==-1 ? 10 : 4));
                  echo "<allmembernum>1</allmembernum>";
                  echo "<userlist>";
                  echo "<user>"; 
                     echo "<uid>".$value['uid']."</uid>";
                     echo "<name>".$value["username"]."</name>";
                     echo "<icon><![CDATA[".$usericon."]]></icon>";
                     echo "<isdefaulticon>-1</isdefaulticon>";
                     echo "<profileurl><![CDATA[".$_SC['siteurl']."space.php?uid=".$value['uid']."]]></profileurl>";
                     echo "<sex>".$genders."</sex>"; 
                     echo "<bday>".$bday."</bday>";
                     echo "<province>".$value['resideprovince']."</province>";
                     echo "<city>".$value['residecity']."</city>";
                     echo "<level>".$level."</level>";
                  echo "</user>";
                  echo "</userlist>"; 
            }else{
                 echo "<allmembernum>0</allmembernum>";
                 echo "<userlist></userlist>"; 
            }
            return;   
         } 
         $pagesize =  intval($pagesize) > 0 ? intval($pagesize) : 512;
         $pageindex = $pageindex ? intval($pageindex) : 0;
         //为提高性能，2010-05-20修改群成员总数获取sql；另外群成员总数返回为实际值
         $membernum = $_SGLOBAL['db']->result($_SGLOBAL['db']->query("SELECT membernum FROM ".tname('mtag')." WHERE tagid='$gid'"), 0);
         echo "<pageindex>".$pageindex."</pageindex>";
         echo "<pagesize>".$pagesize."</pagesize>";
         echo "<allmembernum>".$membernum."</allmembernum>";
         echo "<userlist>";
         if($membernum){
         	//实际参与计算翻页的群成员总数，仍然限制2000
         	$limitmembernum = min($membernum,2000); 
            $start =  page_start($pageindex, $pagesize, $limitmembernum);
            $query = $_SGLOBAL['db']->query("SELECT t.grade,s.uid,s.username,s.name,s.avatar,sf.sex,sf.birthyear,sf.birthmonth,sf.birthday,sf.resideprovince,sf.residecity 
                     FROM (SELECT grade,uid FROM ".tname('tagspace')." WHERE tagid='$gid' AND grade!='-2' LIMIT $start,$pagesize) t
                     LEFT JOIN ".tname('space')." s ON t.uid=s.uid
                     LEFT JOIN ".tname('spacefield')." sf ON sf.uid=s.uid");
            while($value = $_SGLOBAL['db']->fetch_array($query)){
                   //是否开启实名认证  
                  if($_SCONFIG['realname'] && $value['name']){ 
                     $value["username"] = im_xmlsafestr(htmlspecialchars($value['name']));
                  }else{
                     $value["username"] = im_xmlsafestr(htmlspecialchars($value['username']));
                  }
                  $usericon = im_avatar($value['uid'],middle,true);
                  //2：（创建人）；3：（管理员）；4：（普通用户）；10：（禁言） 
                  $level = ($value['grade']==9) ? 2 :($value['grade']==8 ? 3 :($value['grade']==-1 ? 10 : 4));
                  $genders = $value['sex']==0 ? -1 : ($value['sex']==1 ? "male" : "female");
                  $bday = sprintf('%04d-%02d-%02d', $value['birthyear'], $value['birthmonth'], $value['birthday']);
                  $bday = ($bday=='0000-00-00') ? "" : $bday;
                  echo "<user>"; 
                     echo "<uid>".$value['uid']."</uid>";
                     echo "<name>".$value["username"]."</name>";
                     echo "<icon><![CDATA[".$usericon."]]></icon>";
                     echo "<isdefaulticon>-1</isdefaulticon>";
                     echo "<profileurl><![CDATA[".$_SC['siteurl']."space.php?uid=".$value['uid']."]]></profileurl>";
                     echo "<level>".$level."</level>"; 
	                 echo "<sex>".$genders."</sex>"; 
	                 echo "<bday>".$bday."</bday>";
	                 echo "<province>".$value['resideprovince']."</province>";
	                 echo "<city>".$value['residecity']."</city>";   
                  echo "</user>";
            }
         } 
         echo "</userlist>"; 
    }
   
   //17-返回所查询群的详细信息
   function getGroupProfile($gid, $groupkey){
        if(!groupkey_login($gid,$groupkey)){
             return;
        }
        global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN;
        $gid = intval($gid);
        $query = $_SGLOBAL['db']->query("SELECT tagid,tagname,membernum,announcement,pic,viewperm,joinperm FROM ".tname('mtag')." WHERE tagid='$gid'"); 
        echo "<groupprofile>"; 
        while($value = $_SGLOBAL['db']->fetch_array($query)){
             $gname = im_filtstr($value['tagname']);
             $notice = im_filtstr($value['announcement']);
             $joinauth = $value['joinperm'];
             echo "<gid>".$value['tagid']."</gid>";
             echo "<gname><![CDATA[".$gname."]]></gname>";
             echo "<headurl><![CDATA[".$value['pic']."]]></headurl>";
             echo "<notice><![CDATA[".$notice."]]></notice>";
             echo "<joinauth>".$value['joinperm']."</joinauth>";
        }
        echo "</groupprofile>";
   }
   
   //18-返回群成员人数或级别是否发生变化
   function getGroupMemberchange($gid, $groupkey){
        global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $imversion;
        if(!groupkey_login($gid,$groupkey)){
             return;
        }
        $gid = intval($gid);
        $query = $_SGLOBAL['db']->query("SELECT uid,grade FROM ".tname('tagspace')." WHERE tagid='$gid' AND grade!='-2' LIMIT 0,1000");
        $hrshvalue = "";
        while($value = $_SGLOBAL['db']->fetch_array($query)){
              //2：（创建人）；3：（管理员）；4：（普通用户）；10：（禁言） 
              $level = ($value['grade']==9) ? 2 :($value['grade']==8 ? 3 :($value['grade']==-1 ? 10 : 4));
              $hrshvalue .= $value['uid'].$level; 
        }  
        $hrshvalue = md5($hrshvalue);
        echo "<hashvalue>".$hrshvalue."</hashvalue>";  
   }

   //19- 群组的最近动态
   function getGroupActivity($gid, $groupkey, $time, $maxnum){
         global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $imversion;
         if(!groupkey_login($gid,$groupkey)){
             return;
         }
         $gid = intval($gid);
         $querytime = $time ? $_SGLOBAL['timestamp']-intval($time) : $_SGLOBAL['timestamp']-3600*24*3;
         $maxnum = intval($maxnum) > 0 ? intval($maxnum) : 20;
         if(empty($_SC['siteurl'])) $_SC['siteurl'] = str_replace(SUB_DIR,'/',getsiteurl());
         echo "<groupactivity>";
         //2010-03-22,将以发起话题时间排序，修改为以回复话题时间排序，以提高性能
         $query = $_SGLOBAL['db']->query("SELECT t.uid,t.username,t.subject,t.viewnum,t.replynum,t.dateline,t.tid,p.message 
         	 							  FROM (SELECT uid,username,subject,viewnum,replynum,dateline,tid FROM ".tname('thread')." WHERE tagid='$gid' AND displayorder>=0 AND dateline>='$querytime' ORDER BY displayorder DESC,lastpost DESC LIMIT 0,$maxnum) t
                                          LEFT JOIN ".tname('post')." p ON t.tid=p.tid AND p.isthread='1'");
         while($value = $_SGLOBAL['db']->fetch_array($query)){
              $value['profileurl'] = $_SC['siteurl']."space.php?uid=".$value['uid'];
              $value["username"] = ($_SCONFIG['realname'] && $value['namestatus']) ? $value['name'] : $value['username'];
              $value["username"] = im_xmlsafestr(htmlspecialchars($value["username"]));
              $value['usericon'] = im_avatar($uid,middle,true);
              $value['type'] = "发起话题";
              //以下是截取标题和内容的前80个字符 ，并还原用户可能输入的一些特殊字符 
              $value['title'] = getstr(im_filtstr($value['subject']),80,1,0,0,0,-1);
              $value['content'] = getstr(im_filtstr($value['message']),80,1,0,0,0,-1);
              //获取内容中的第一张图片
              if(preg_match("/<IMG.*file=\"(.*)\"*?>/i",$value['message'],$matches)){
                   $value['image'] = $_SC['siteurl'].$matches[1]; 
              }else{
                   $value['image'] = "";
              }
              echo "<activity>";
                  echo "<user uid=\"".$value['uid']."\" url=\"".$value['profileurl']."\">".$value["username"]."</user>";
                  echo "<icon><![CDATA[".$value["usericon"]."]]></icon>";
                  echo "<isdefaulticon>-1</isdefaulticon>"; 
                  echo "<type>".$value['type']."</type>"; 
                  echo "<title><![CDATA[".$value['title']."]]></title>"; 
                  echo "<content><![CDATA[".$value['content']."]]></content>";
                  echo "<time>".$value['dateline']."</time>";
                  echo "<url><![CDATA[". $_SC['siteurl']."space.php?uid=".$value['uid']."&do=thread&id=".$value['tid']."]]></url>";  
                  echo "<image><![CDATA[".$value['image']."]]></image>";
                  echo "<pageviews>".$value['viewnum']."</pageviews>";
                  echo "<comments>".$value['replynum']."</comments>";
              echo "</activity>";
        }
        echo "</groupactivity>";
   }
   
   //-----------------------------辅助函数-------------------------------//
  //获取用户空间信息
  function getspace_imxml($key, $indextype='uid') {
       global $_SGLOBAL, $_SCONFIG;
       $space = array();
       $query = $_SGLOBAL['db']->query("SELECT sf.*, s.* FROM ".tname('space')." s
    		    LEFT JOIN ".tname('spacefield')." sf ON sf.uid=s.uid
    		    WHERE s.uid='$key'");
       if(!$space = $_SGLOBAL['db']->fetch_array($query)) {
     			//return false;
       }
       return $space;
  }
  //处理特殊用户名       
  function im_xmlsafestr($s){ 
       return preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/",'',$s);
  }
  
  //好友列表的页数
  function page_start($page, $ppp, $totalnum) {
        $totalpage = ceil($totalnum / $ppp);
        $page =  max(0, min($totalpage,intval($page)));
        return $page * $ppp;
  }
  //userkey验证用户登录
  function sitekey_login($queryuserid, $userkey) {
        global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $im_sitekey, $imversion;
        echo '<version>'.$imversion.'</version>';
        if(!$queryuserid){
            echo "<error>no uid param valid</error>";
            echo "<userkeyvalide>false</userkeyvalide>";
            return false;
        }
        if(!$userkey){
            echo "<error>no userkey param valid</error>";
            echo "<userkeyvalide>false</userkeyvalide>";
            return false;
        }
        
        dbconnect();   
        $_SGLOBAL['supe_uid'] = intval($queryuserid);
        $tempkey = md5($queryuserid.$im_sitekey);
        if($tempkey == $userkey){
            echo "<userkeyvalide>true</userkeyvalide>";
            return true;
        }else{
              echo "<userkeyvalide>false</userkeyvalide>";
              return false;
        }
  }
  //groupkey验证用户登录 
  function groupkey_login($gid,$groupkey){
       global $_SGLOBAL, $_SC, $_SCONFIG, $_SCOOKIE, $_SN, $im_sitekey, $imversion;
       echo '<version>'.$imversion.'</version>';
       if(!$gid){
            echo "<error>群组id错误</error>";
            return false;
        }
        if(!$groupkey){
            echo "<error>no groupkey</error>";
            return false;
        }
        dbconnect();
        $tempkey = md5($gid.$im_sitekey);
        if($tempkey == $groupkey){
            return true;
        }else{
              echo "<error>groupkey invalid</error>";
              return false;
        } 
  }
  //活动类型的变换
  function imactivitytype($type){
       //活动类型
       $types = array('blog', 'album', 'friend', 'mtag', 'thread', 'post', 'comment', 'doing');
       $imtypes = array('发表日志', '上传图片', '成为好友', '加入群组', '发起话题', '回复话题', '评论了', '记录道');
       if(in_array($type,$types)){
           if($type=="album"){
              $mark = 1;
           }elseif($type=="mtag" || $type=="doing"){
                $mark = 2;
           }elseif($type=="blog" || $type=="thread"){
                $mark = 3;
           }elseif($type=="comment" || $type=="post" ){
                $mark = 4;
           }elseif($type=="friend"){
                $mark = 5;
           }
           $type = str_replace($types,$imtypes,$type);  
       }else{
           $mark = 0;
       }
       return array($mark,$type);
  }
  //处理用户输入内容中可能的特殊字符
  function im_filtstr($str){
        $str = str_replace(array('&amp;','&quot;','&lt;','&gt;','&nbsp;','&#39;'), array('&','"','<','>','','\''), $str);
        $str = im_xmlsafestr($str);
        return $str;
  }
  //处理日志中的照片地址
  function im_mkpicurl($pic){
        global $_SCONFIG, $_SC, $space;
        $url = '';
        if($pic['picflag'] == 1) {
            $url = $_SC['attachurl'].$pic['pic'];
        }elseif($pic['picflag'] == 2) {
                $url = $_SCONFIG['ftpurl'].$pic['pic'];
        }else{
              $url = $pic['pic'];
        }
        return $url;
  }
  //获得用户组名
  function im_getfriendgroup($userinfo) {
	   global $_SCONFIG;
	   $groups = array();
	   $space = unserialize($userinfo['privacy']);
	   $spacegroup = empty($space['groupname'])?array():$space['groupname'];
	   for($i=0; $i<$_SCONFIG['groupnum']; $i++) {
			if($i == 0){
				$groups[0] = lang('friend_group_default');
			}else{
				 if(!empty($spacegroup[$i])){
					  $groups[$i] = $spacegroup[$i];
				 }else{
					  if($i<8) {
						   $groups[$i] = lang('friend_group_'.$i);
					  }else{
						   $groups[$i] = lang('friend_group').$i;
					  }
				 }
			}
	   }
	   return $groups;
  }
  //得到头像
  function im_avatar($uid, $size) {
       global $_SGLOBAL, $_SCONFIG;
       $type = empty($_SCONFIG['avatarreal']) ? 'virtual' : 'real';
       $uid = abs(intval($uid));
       $uid = sprintf("%09d", $uid);
       $dir1 = substr($uid, 0, 3);
       $dir2 = substr($uid, 3, 2);
       $dir3 = substr($uid, 5, 2);
       $typeadd = $type == 'real' ? '_real' : '';
       $file = UC_API.'/data/avatar/'.$dir1.'/'.$dir2.'/'.$dir3.'/'.substr($uid, -2).$typeadd."_avatar_$size.jpg";
       return $file;
  }
  //好友uid安全性检查
  function uid_safecheck($fuids,$fnum){
       if(!$fuids){
            return '';
       }
       $_fuid = explode(',',$fuids);
       if(count($_fuid)>$fnum){
            return '';
       }
       $_fuids = '';
       $i = 0;
       foreach($_fuid as $_tmpuid){
            //验证是否为数字uid
            if(is_numeric($_tmpuid)){
                if($i>=100){
                     break;
                }
                $_fuids =  $_fuids ? $_fuids.','.$_tmpuid : $_tmpuid;
                $i++;
            }else{
                 break;
            }
       }
       if($_fuids){
            return $_fuids;
       }else{
            return '';
       }
  }
?>